<script setup lang="ts">
import axios from "axios";
import { message } from "@/utils/message";
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

import type { UploadProps } from "element-plus";

const imageUrl = ref("");
const fileExist = ref(false);
const useUploadImage = ref(false); // 判断是否使用上传的图片
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
};
/** 上传文件前校验 */
const beforeAvatarUpload: UploadProps["beforeUpload"] = rawFile => {
  if (!["image/jpeg", "image/png", "image/gif"].includes(rawFile.type)) {
    message("只能上传图片");
    return false;
  }
  const isExceed = rawFile.size / 1024 / 1024 > 2;
  if (isExceed) {
    message(`单个图片大小不能超过2MB`);
    return false;
  }
};
defineOptions({
  name: "PureUpload"
});

/** 超出最大上传数时触发 */
const onExceed = () => {
  message("最多上传1张图片，请先删除在上传");
};

const onSuccess = (e, file) => {
  console.log("onSuccess", e, file);
};
const onError = (e, file) => {};

const noUpload = () => {
  useUploadImage.value = false;
  fileExist.value = true;
};

const onChange = (e, file) => {
  const url = URL.createObjectURL(e.raw);
  imageUrl.value = url;
  fileExist.value = true;
  useUploadImage.value = true;
  // 释放资源
  // URL.revokeObjectURL(url);
};

import ReCropper from "@/components/ReCropper";
import { formatBytes } from "@pureadmin/utils";

defineProps({
  imgSrc: String
});

const emit = defineEmits(["cropper"]);

const infos = ref();
const popoverRef = ref();
const refCropper = ref();
const showPopover = ref(false);
const cropperImg = ref<string>("");

function onCropper({ base64, blob, info }) {
  infos.value = info;
  cropperImg.value = base64;
  emit("cropper", { base64, blob, info });
}

function hidePopover() {
  popoverRef.value.hide();
}

// 统一关闭逻辑
const handlePopoverClose = () => {
  hidePopover();
};
defineExpose({ hidePopover });
</script>

<template>
  <el-card v-if="!fileExist" shadow="never">
    <el-upload
      class="avatar-uploader"
      action=""
      :auto-upload="false"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :on-change="onChange"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
    <!-- 修改原来图片按钮：放置在上传区域下方 -->
    <el-button
      v-if="!fileExist"
      @click="noUpload()"
      size="default"
      style="margin-top: 10px"
    >
      修改原来图片
    </el-button>
    <p class="el-upload__tip">
      可拖拽上传，不超过2MB且格式为jpeg/png/gif的图片
    </p>
    <el-divider />
  </el-card>
  <div v-else v-loading="!showPopover" element-loading-background="transparent">
    <el-popover
      ref="popoverRef"
      :visible="showPopover"
      placement="right"
      width="18vw"
      @before-leave="handlePopoverClose"
    >
      <template #reference>
        <div class="w-[18vw]">
          <ReCropper
            ref="refCropper"
            :src="useUploadImage ? imageUrl : imgSrc"
            circled
            @cropper="onCropper"
            @readied="showPopover = true"
          />
          <p v-show="showPopover" class="mt-1 text-center">
            温馨提示：右键上方裁剪区可开启功能菜单
          </p>
        </div>
      </template>
      <div class="flex flex-wrap justify-center items-center text-center">
        <el-image
          v-if="cropperImg"
          :src="cropperImg"
          :preview-src-list="Array.of(cropperImg)"
          fit="cover"
        />
        <div v-if="infos" class="mt-1">
          <p>
            图像大小：{{ parseInt(infos.width) }} ×
            {{ parseInt(infos.height) }}像素
          </p>
          <p>
            文件大小：{{ formatBytes(infos.size) }}（{{ infos.size }} 字节）
          </p>
        </div>
      </div>
    </el-popover>
  </div>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: contain;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
